import React, { useEffect } from 'react';
import _ from 'lodash';
import fp from 'lodash/fp';
import { append } from '../utils';

/**
 * 将页码分割为二维数组保存
 *
 * @param {*} str '2-5-8,7-3-1'
 */
const getDoubleDimensionalArray = str =>
  str.split(',').map(range => {
    const fn = _.flowRight(
      array => array.sort((a, b) => a - b), // [7,3,1] 排序为 [1,3,7]
      fp.map(item => parseInt(item, 10)), // ['2', '5', '8'] 转换为 [2, 5, 8]
      fp.split('-'), // 2-5-8 切割为 ['2', '5', '8']
    );
    const arr = fn(range);
    return [arr[0], arr[arr.length - 1]]; // 仅返回首尾两个数字
  });

/**
 * 将二维数组拍平为不重复的一维数组
 *
 * @param {*} arr 二维数组 [1, 4]
 */
const flatDoubleDimensionalArray = arr =>
  // acc: [1, 2, 3, 4], currentRange: [1, 4]
  arr.reduce((acc, currentRange) => {
    for (let i = currentRange[0]; i <= currentRange[1]; i += 1) {
      if (!acc.some(num => num === i)) {
        acc.push(i);
      }
    }
    return acc;
  }, []);

function main() {
  const fn = _.flowRight(
    arr => arr.sort((a, b) => a - b),
    flatDoubleDimensionalArray,
    getDoubleDimensionalArray,
  );
  const fnOdd = _.flowRight(arr => arr.filter(num => num % 2 === 1), fn);
  const fnEven = _.flowRight(arr => arr.filter(num => num % 2 === 0), fn);

  append(`测试用例1：${JSON.stringify(fn('1-8-7,2-5-3,,'))}`); // [1,2,3,4,5,6,7,8]
  append(`测试用例2：${JSON.stringify(fn('5-8,1-3'))}`); // [1,2,3,5,6,7,8]
  append(`测试用例3：${JSON.stringify(fn('8-5,6-4'))}`); // [4,5,6,7,8]
  append(`测试用例4：${JSON.stringify(fnOdd('1-8'))}`); // [1,3,5,7]
  append(`测试用例4：${JSON.stringify(fnEven('1-8'))}`); // [2,4,6,8]
}

export default function PageNumberDemo() {
  useEffect(main, null);
  return (
    <div id="content">
      <p>PageNumber</p>
    </div>
  );
}
